import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
const Home = () => import('@/views/home/index.vue')
const Login = () => import('@/views/login/index.vue')
const Question = () => import('@/views/question/index.vue')
const Video = () => import('@/views/video/index.vue')
const User = () => import('@/views/user/index.vue')
const Profile = () => import('@/views/user/profile.vue')
const Chat = () => import('@/views/user/chat.vue')
const Article = () => import('@/views/article/index.vue')
const Tabbar = () => import('@/components/app-tabbar.vue')
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login,
    meta: {}
  },
  {
    path: '/',
    alias: '/home',
    components: {
      default: Home,
      bottom: Tabbar
    }
  },
  {
    path: '/question',
    components: {
      default: Question,
      bottom: Tabbar
    }
  },
  {
    path: '/video',
    components: {
      default: Video,
      bottom: Tabbar
    }
  },
  {
    path: '/user',
    components: {
      default: User,
      bottom: Tabbar
    },
    meta: {
      needLogin: true // 需要登录才可访问
    }
  },
  {
    path: '/user/profile',
    component: Profile,
    meta: {
      needLogin: true // 需要登录才可访问
    }
  },
  {
    path: '/user/chat',
    component: Chat,
    meta: {
      needLogin: true // 需要登录才可访问
    }
  },
  {
    path: '/article/:id', // 配置动态路由
    components: {
      default: Article
    }
  }
]

const router = new VueRouter({
  routes
})
// 导航守卫
// const whitePath = ['/user', '/user/profile', '/user/chat']
router.beforeEach((to, from, next) => {
  console.log(to)
  if (store.getters['user/getToken']) {
    if (to.path.toLowerCase() === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    // if (to.path.toLowerCase().startsWith('/user')) {
    // 白名单写法
    // if (whitePath.includes(to.path.toLowerCase())) {
    // 路由元写法
    if (to.meta.needLogin) {
      // 路由传参想去的路由
      next('/login?redirect=' + to.fullPath)
    } else {
      next()
    }
  }
})
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return routerPush.call(this, location).catch(error => error)
}

export default router
